package com.taotao.service;

import com.alibaba.fastjson.JSON;
import com.taotao.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author wangjin
 * @title: IndexService
 * @projectName sw-gateway
 * @description:
 * @date 2021/12/9 18:00
 */
@RestController
@Slf4j
public class IndexService {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    /**
     * 批量新增文档
     */
    @RequestMapping("/bulkAddDoc")
    public void bulkAddDoc() {
        // 1.构建批量新增BulkRequest请求对象
        BulkRequest bulkRequest = new BulkRequest();

        // 2.准备需要保存到索引库的Json文档数据封装到IndexRequest请求对象中
        for (long i = 2; i < 9; i++) {
            // 2.1准备需要保存到索引库的Json文档数据
            Product product = new Product(i, "小米手机" + i, "手机", "小米", 2899.00 + i, "http://www.baidu.com");
            String jsonString = JSON.toJSONString(product);
            // 2.2创建请求对象,指定索引库、类型、id(可选)
            IndexRequest indexRequest = new IndexRequest("bntang", "product", "" + i);
            // 2.3将请求数据封装到IndexRequest请求对象中
            indexRequest.source(jsonString, XContentType.JSON);
            // 3.添加IndexRequest请求对象至批量新增BulkRequest请求对象
            bulkRequest.add(indexRequest);
        }

        try {
            // 4.调用方法进行数据通信
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/index")
    public String mayikt(Long id) {
        log.info("<index  logs id:{}>", id);
        return "ok" + 1 % id;
    }
}
